import React from "react";
import { Modal, Table, Input, message } from "antd";
import _uniqBy from "lodash/uniqBy";
import { connect } from "dva";
import styles from "./TransferSeclet.less";
import UsersTags from "../usersTags/UsersTags";

import {openNotificationWithIcon} from "../../utils/comm.js";

const { Search } = Input;

const columns = [
  {
    title: "用户工号",
    dataIndex: "employeeCode",
    key: "employeeCode",
  },
  {
    title: "用户姓名",
    dataIndex: "employeeName",
    key: "employeeName",
  },
  {
    title: "所属组织",
    dataIndex: "orgName",
    key: "orgName",
    render: (text, record) =>
      record.orgList.map(item => item.orgName).join("，"),
  },
];

@connect(({
  usertreeSelect,
  loading,
}) => ({
  loading,
  usertreeSelectStore: usertreeSelect,
}))
class TransferSeclet extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.treeRef = {};
    this.state = {
      keyWord: "",
      pageNum: 1,
      pageSize: 6,
      totalCount: 0,
      listData: [],
      selectedRowKeys: [],
      selectDatas: [],
    };
  }

  componentDidMount() {
  }

  deleteData = (data = []) => {
    const { selectedRowKeys } = this.state;
    if (data.length === 0) {
      this.setState({
        selectedRowKeys: [],
      });
      return;
    }
    const resultData = [];
    selectedRowKeys.map(t => {
      if (!data.includes(t)) {
        resultData.push(t);
      }
      return null;
    });
    this.setState({
      selectedRowKeys: resultData,
    });
  };

  // 删除项
  handleDelSelect = delItem => {
    const {type, code} = delItem || {};
    const {selectDatas} = this.state;
    this.setState({selectDatas: selectDatas.filter(sItem => {
      return !(sItem.type === type && sItem.code === code);
    })});
    this.deleteData([code]);
  };

  // 清除
  handleClearSelect = () => {
    this.setState({selectDatas: []}, () => {
      this.deleteData([]);
    });
  };

  // 确定
  handleUsersSelect = () => {
    const { selectDatas } = this.state;
    const { dispatch, onCancel, initData, initSelectedTaskKeys, selectedTaskKeys } = this.props;
    if (selectDatas?.length === 0) {
      message.warning("请选择一个办理人");
    } else if (selectDatas?.length > 1) {
      message.warning("最多只能选择一个办理人");
    } else {
      dispatch({
        type: "FlowMonitor/BatchTurnTasks",
        payload: {
          taskIds: selectedTaskKeys,
          turnToUserCode: selectDatas[0]?.code,
        },
      }).then((res) => {
        if (res.success === true) {
          message.success(res.datas);
          onCancel();
          initData();
          initSelectedTaskKeys();
          setTimeout(() => {
            this.setState({
              totalCount: 0,
              listData: [],
              pageNum: 1,
              selectedRowKeys: [],
              selectDatas: [],
            });
          }, 100);
        } else { 
          message.error(res.errMsg);
        }
      })
    }
  };

  handleCancel = () => {
    const {onCancel} = this.props;
    if (onCancel) {
      onCancel();
      this.setState({
        totalCount: 0,
        listData: [],
        pageNum: 1,
        selectedRowKeys: [],
        selectDatas: [],
      });
    }
  };

  handleChange = e => {
    this.setState(
      {
        keyWord: e,
      },
      () => {
        this.onSearch();
      },
    );
  };

  onSearch = () => {
    this.searchEmployeeList();
  };

  searchEmployeeList = () => {
    const { dispatch } = this.props;
    const { pageNum, pageSize, keyWord } = this.state;
    dispatch({
      type: "usertreeSelect/selectEmployeeList",
      payload: { employeeName: keyWord, pageIndex: pageNum, pageSize },
    }).then(({ errCode, errMsg, datas }) => {
      if (errCode === 0) {
        this.setState({
          listData: datas.dataList,
          totalCount: datas.total,
        });
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "搜索失败");
      }
    });
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    if (selectedRows.some(d => !d.userId)) {
      message.warning("userId为空，请核实用户数据");
      return;
    }
    this.handleSelected(selectedRowKeys, selectedRows);
  };

  handleSelected = selectedRowKeys => {
    this.setState({ selectedRowKeys });
    const { listData, selectDatas } = this.state;
    const result = [...selectDatas].filter(d => d.type === "STA")
    .filter(d => selectedRowKeys.includes(d.code));;
    listData.map(item => {
      if (selectedRowKeys.includes(item.userId)) {
        result.push({
          type: "STA",
          code: item.userId,
          name: item.employeeName,
        });
      }
      return null;
    });
    this.setState({selectDatas: _uniqBy([...result], "code")})
  };

  changePage = pageNum => {
    this.setState({ pageNum }, () => {
      this.onSearch();
    });
  };

  changePageSize = (_, pageSize) => {
    this.setState({ pageNum: 1, pageSize }, () => {
      this.onSearch();
    });
  };


  render() {
    const {
      visible,
      wrapClassName,
      loading,
    } = this.props;
    const {
      selectDatas,
      selectedRowKeys,
      pageNum,
      pageSize,
      listData,
      totalCount,
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const listLoading =
    loading.effects["usertreeSelect/selectEmployeeList"] || false;

    return (
      <Modal
        title="选择办理人"
        centered
        width={668}
        destroyOnClose
        visible={visible}
        onOk={this.handleUsersSelect}
        onCancel={this.handleCancel}
        wrapClassName={`${styles.user_modal} ${wrapClassName}`}
      >
        <div className={styles.transactor_box}>
          <div className={styles.select_box}>
            <span className={styles.label}>
              已选择办理人：
            </span>
            <div className={styles.user_list}>
              {selectDatas.map(item => (
                <UsersTags
                  key={`${item.type}_${item.code}`}
                  label={item.name}
                  onClick={() => this.handleDelSelect(item)}
                />
              ))}
            </div>
            {selectDatas.length > 0 && (
              <span className={styles.clear} onClick={this.handleClearSelect}>
                清空
              </span>
            )}
          </div>
          <div className={styles.tree_box}>
            <Search
              style={{ margin: "12px 0", width: 300 }}
              placeholder="请输入用户姓名或者工号"
              onSearch={this.handleChange}
            />
            <Table
              columns={columns}
              size="small"
              rowKey="userId"
              rowSelection={rowSelection}
              dataSource={listData}
              loading={listLoading}
              pagination={{
                size: "small",
                showSizeChanger: true,
                showQuickJumper: true,
                onChange: this.changePage,
                onShowSizeChange: this.changePageSize,
                pageSize,
                current: pageNum,
                total: totalCount,
                pageSizeOptions: ["6", "10", "20", "30"],
              }}
            />
          </div>
        </div>
      </Modal>
    );
  }
}

export default TransferSeclet;
